package com.erik.ipmonitor.repository;

import com.erik.ipmonitor.model.po.Project;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import java.util.List;

public class ProjectRepositoryImpl extends SimpleJpaRepository<Project, Long> implements ProjectRepository {

    private final EntityManager entityManager;

    public ProjectRepositoryImpl(EntityManager entityManager) {
        super(Project.class, entityManager);
        this.entityManager = entityManager;
    }


    @Override
    public Page<Project> findByKeyword(String whereClause, Pageable pageable) {
        // 构建基础SQL
        StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM project");

        // 拼接动态条件（直接拼接字符串，不做参数化）
        if (whereClause != null && !whereClause.trim().isEmpty()) {
            sqlBuilder.append(" WHERE ").append(whereClause);
        }
        // 创建查询
        Query query = entityManager.createNativeQuery(sqlBuilder.toString(), Project.class);
        // 设置分页
        query.setFirstResult((int) pageable.getOffset());
        query.setMaxResults(pageable.getPageSize());
        // 执行查询
        List<Project> content = query.getResultList();
        // 计算总条数
        String countSql = "SELECT COUNT(*) FROM project" +
                (whereClause != null && !whereClause.trim().isEmpty() ? " WHERE " + whereClause : "");
        Long total = ((Number) entityManager.createNativeQuery(countSql).getSingleResult()).longValue();
        return new PageImpl<>(content, pageable, total);
    }
}
